package com.eascs.web.o2o.report.service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UuidUtil;
import com.eascs.notify.constant.ModelResult;
import com.eascs.notify.email.EmailSender;
import com.eascs.notify.email.entity.EmailContentEntity;
import com.eascs.notify.email.entity.EmailSourceSetting;
import com.eascs.notify.mail.MailNotifier;
import com.eascs.notify.mail.MailNotifyRequest;
import com.eascs.notify.mail.MailNotifyResponse;
import com.eascs.notify.mail.MailSendType;
import com.eascs.web.o2o.report.dao.WorkflowReportDao;

@Service
public class BuildEmailService {
	
	protected final Logger logger =LoggerFactory.getLogger(getClass());
	
	
	@Autowired
	EmailSourceSetting emailSourceSetting;
	@Autowired
	private EmailSender emailSender;
	
	@Inject
	WorkflowReportDao workflowReportDao;
	@Reference
	MailNotifier mailNotifier;
	
	@Value("${email.toemail.dev}")
	String devmail;
	
	@Value("${email.toemail.refund}")
	String refundmail;
	
	
	
	/*
	 * 发送邮件--每周信贷经理贷款投放统计及排名（邮件发送和入库是两个分开的方法）
	 */
	public void creditManagerRankMail() {
		logger.info("=============开始发送邮件--每周信贷经理贷款投放统计及排名===============");
		ArrayList<String> listDirectories=new ArrayList<String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Calendar c =Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.MONTH,-1);
		String date = sdf.format(c.getTime());
		String excelPath = date+"_managerRank";
		String title = "信贷经理贷款投放统计及排名" + date;
		if(listDirectories==null||listDirectories.size()==0){
			IoUtil.createDirectorieIfMissing(new File(emailSourceSetting.getFilepath()+"/"+excelPath).getParentFile());
			listDirectories.add(emailSourceSetting.getFilepath()+"/"+excelPath); 
		}
		EmailContentEntity entity = new EmailContentEntity();
		entity.setHost(emailSourceSetting.getHost());
		entity.setUsername(emailSourceSetting.getFrom());
		entity.setPassword(emailSourceSetting.getPassword());
		entity.setFrom(emailSourceSetting.getFrom());
		entity.setSubject(title);
		entity.setContent(title);
		
		String[] receivers = emailSourceSetting.getToCreditManager().split(",");
		//list去重
		HashSet<String> h = new  HashSet<String>(listDirectories); 
		listDirectories.clear(); 
		listDirectories.addAll(h); 
		entity.setAttachmentDirectories(listDirectories);
		
		
		MailNotifyRequest mailNotifyRequest=new MailNotifyRequest();
		mailNotifyRequest.setTitle(title);
		mailNotifyRequest.setContent(title);
		mailNotifyRequest.setSystemCode("报表系统");
		mailNotifyRequest.setMailSendType(MailSendType.INSTANT);
		mailNotifyRequest.setRequestId(UuidUtil.generateShortUuid());
		mailNotifyRequest.setRequestDateTime(new Date());
		mailNotifyRequest.setBizCode("信贷经理贷款投放统计及排名");
		mailNotifyRequest.setAttachmentPath(emailSourceSetting.getFilepath()+"/"+excelPath);
		for(String receiver : receivers){
			entity.setTo(receiver);
			emailSender.send(entity);//发邮件
			
			ModelResult<MailNotifyResponse> model = null;
			
			mailNotifyRequest.setRecipientTo(receiver);
			try {
				model = mailNotifier.notify(mailNotifyRequest);//入库
				if(model.isSuccess()){
					workflowReportDao.excuteSql("update wf_email set status = 1 where request_id = ?", model.getModel().getResponseId());
					logger.info("入库成功-文件路径：[{}]，收件人：[{}]",listDirectories,receiver);
				}
			} catch (Exception e) {
				logger.error("邮件发送接口调用异常", e.getMessage());
				e.printStackTrace();
			}
		}
		logger.info("=============结束发送邮件--每周信贷经理贷款投放统计及排名===============");
	}
	

	
	
	
	
	/*
	 * 发送邮件--每周信贷经理贷款投放统计及排名（邮件发送和入库是两个分开的方法）
	 */
	public void provinceBusinessRankMail() {
		logger.info("=============开始发送邮件--每周全国各省区贷款投放排名===============");
		ArrayList<String> listDirectories=new ArrayList<String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Calendar c =Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.MONTH,-1);
		String date = sdf.format(c.getTime());
		String excelPath = date+"_businessRank";
		String title = "全国各省区贷款投放排名" + date;
		if(listDirectories==null||listDirectories.size()==0){
			IoUtil.createDirectorieIfMissing(new File(emailSourceSetting.getFilepath()+"/"+excelPath).getParentFile());
			listDirectories.add(emailSourceSetting.getFilepath()+"/"+excelPath); 
		}
		EmailContentEntity entity = new EmailContentEntity();
		entity.setHost(emailSourceSetting.getHost());
		entity.setUsername(emailSourceSetting.getFrom());
		entity.setPassword(emailSourceSetting.getPassword());
		entity.setFrom(emailSourceSetting.getFrom());
		entity.setSubject(title);
		entity.setContent(title);
		
		String[] receivers = emailSourceSetting.getToCreditManager().split(",");
		//list去重
		HashSet<String> h = new  HashSet<String>(listDirectories); 
		listDirectories.clear(); 
		listDirectories.addAll(h); 
		entity.setAttachmentDirectories(listDirectories);
		
		
		MailNotifyRequest mailNotifyRequest=new MailNotifyRequest();
		mailNotifyRequest.setTitle(title);
		mailNotifyRequest.setContent(title);
		mailNotifyRequest.setSystemCode("报表系统");
		mailNotifyRequest.setMailSendType(MailSendType.INSTANT);
		mailNotifyRequest.setRequestId(UuidUtil.generateShortUuid());
		mailNotifyRequest.setRequestDateTime(new Date());
		mailNotifyRequest.setBizCode("全国各省区贷款投放排名");
		mailNotifyRequest.setAttachmentPath(emailSourceSetting.getFilepath()+"/"+excelPath);
		for(String receiver : receivers){
			entity.setTo(receiver);
			emailSender.send(entity);//发邮件
			
			ModelResult<MailNotifyResponse> model = null;
			
			mailNotifyRequest.setRecipientTo(receiver);
			try {
				model = mailNotifier.notify(mailNotifyRequest);//入库
				if(model.isSuccess()){
					workflowReportDao.excuteSql("update wf_email set status = 1 where request_id = ?", model.getModel().getResponseId());
					logger.info("入库成功-文件路径：[{}]，收件人：[{}]",listDirectories,receiver);
				}
			} catch (Exception e) {
				logger.error("邮件发送接口调用异常", e.getMessage());
				e.printStackTrace();
			}
		}
		logger.info("=============结束发送邮件--每周全国各省区贷款投放排名===============");
	}
	
	
	
	
	
	/*
	 * 发送邮件--日邮件
	 */
	public void job_sendMail() {
		logger.info("=============开始发送邮件--日邮件===============");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ArrayList<String> listDirectories=new ArrayList<String>();
		String date = sdf.format(new Date());
		if(listDirectories==null||listDirectories.size()==0){
			IoUtil.createDirectorieIfMissing(new File(emailSourceSetting.getFilepath()+"/"+date).getParentFile());
			listDirectories.add(emailSourceSetting.getFilepath()+"/"+date); 
		}
		mailSendOneByOne(listDirectories, "O2O金融报表-",date,true);
		logger.info("=============结束发送邮件--日邮件===============");
	}
	
	
	
	/*
	 * 发送邮件,一个一个人的发送<br>
	 * 避免因为某个人的邮箱失效导致所有人都无法成功接受邮件
	 */
	public void mailSendOneByOne(ArrayList<String> listDirectories,String title,String date,boolean flag) {
		EmailContentEntity entity = new EmailContentEntity();
		entity.setHost(emailSourceSetting.getHost());
		entity.setUsername(emailSourceSetting.getFrom());
		entity.setPassword(emailSourceSetting.getPassword());
		entity.setFrom(emailSourceSetting.getFrom());
		entity.setSubject(title + date);
		entity.setContent(title + date);
		
		String[] receivers = emailSourceSetting.getTo().split(",");
		if(flag){
			//list去重
			HashSet<String> h = new  HashSet<String>(listDirectories); 
			listDirectories.clear(); 
			listDirectories.addAll(h); 
			entity.setAttachmentDirectories(listDirectories);
		}else{
			receivers = devmail.split(",");
		}
		
		MailNotifyRequest mailNotifyRequest=new MailNotifyRequest();
		for(String receiver : receivers){
			entity.setTo(receiver);
			emailSender.send(entity);
			mailNotifier.notify(mailNotifyRequest);
		}
		
	}

	
	
	
	
	
	
	
	
	
	
	
	
	

}
